package cn.jdy.plugins.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.authority.entity.User;
import cn.jdy.authority.entity.UserRole;
import cn.jdy.authority.service.UserRoleService;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.NginxPurgeCacheUtil;
import cn.jdy.plugins.entity.Advertising;
import cn.jdy.plugins.entity.Live;
import cn.jdy.plugins.service.AdvertisingService;
import cn.jdy.plugins.service.LiveService;

/***
 * @desc   广告控制类
 * @author lph
 *
 */
@Controller
@RequestMapping("/advertising")
public class AdvertisingCtrl extends BaseCtrl{
	@Autowired
	private AdvertisingService advertisingService;
	@Autowired
	private LiveService liveService;
	@Autowired
	private UserRoleService userRoleService;
	//默认列表路径
	private static String viewName = "redirect:/advertising/list/0?s=";
	private static Long liveId;
	/**
	 * 初始化
	 * @return
	 */
	@RequestMapping("/list/{id}")
	public ModelAndView list(@RequestParam(required = false) Integer s,@PathVariable Long id) {
		ModelAndView mv = new ModelAndView();
		if(s!=null)
			switch(s) {
				case 1: mv.addObject("msg", "保存成功！");break;
				case 2: mv.addObject("msg", "更新成功！");break;
				case 3: mv.addObject("msg", "删除成功！");break;
				case 4: mv.addObject("msg", "操作失败！");break;
				default: break;
			}
		User user = (User) session.getAttribute("user");
		List<UserRole> list = userRoleService.find("userid", user.getId());
		String roleid = "";
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getRoleid()
					.equals("4028b3044de1a396014de1ba2b2e0000")
					|| list.get(i).getRoleid()
							.equals("ff8080814db89f0a014db8d169290000")) {
				roleid = "0";
			}
		}
		Live live = new Live();
//		Live live=liveService.findOne("userid", user.getId());
		live=liveService.findOne("userid", user.getId());
		if(roleid !="0"){
			if(id!=null){
//				mv.addObject("liveName",live.getName());
				mv.addObject("liveId", id);
			}else{
//				mv.addObject("liveName",live.getName());
				mv.addObject("liveId", null);
			}
			
		}else{
			if(id==null){
				if(live!=null){
//					mv.addObject("liveName",live.getName());
					mv.addObject("liveId", live.getId());
				}else{
//					mv.addObject("liveName","0");
					mv.addObject("liveId", 0);
				}
			}else{
				mv.addObject("liveId", id);
			}
			
		}
		liveId=id;
		mv.setViewName("/operate/advertisingList.jsp");
		return mv;
	}
	
	/**
	 * 异步查询
	 * @param Live
	 * @return
	 */
	@RequestMapping("/queryByPage")
	@ResponseBody
	public Map<String, Object> queryByPage(Advertising advertising) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		Long iTotalDisplayRecords = 0L;
		Long iTotalRecords =0L;
		try {
			List<Advertising> dataList = new ArrayList<Advertising>();
			if(null != advertising.getLiveId()){
				if(0 == advertising.getLiveId()){  //获取	全部
					advertising.setLiveId(null);
					dataList = advertisingService.query(advertising);
				}
				dataList = advertisingService.query(advertising);
				iTotalDisplayRecords = advertisingService.count(advertising);
				iTotalRecords = advertisingService.count(advertising);
			}
			jsonMap.put("dataList", dataList);
			jsonMap.put("iTotalDisplayRecords", iTotalDisplayRecords);
			jsonMap.put("iTotalRecords", iTotalRecords);
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询广告异常", e);
		}
		return jsonMap;
	}

	/**
	 * 新增
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit() {
		return edit(null);
	}

	/**
	 * 编辑
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/operate/advertisingDetail.jsp");
		User user = (User) session.getAttribute("user");
		List<UserRole> list = userRoleService.find("userid", user.getId());
		String roleid = "";
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getRoleid()
					.equals("4028b3044de1a396014de1ba2b2e0000")
					|| list.get(i).getRoleid()
							.equals("ff8080814db89f0a014db8d169290000")) {
				roleid = "0";
			}
		}
		if(roleid=="0"&&liveId==0){
			mv.addObject("datalists", liveService.findAll());
		}else if (roleid=="0"&&liveId!=0) {
			mv.addObject("datalists", liveService.find("mainid",liveService.findOne("id",liveId).getMainid()));
		} else{
			mv.addObject("datalists", liveService.find("userid", user.getId()));
		}
		mv.addObject("liveId", liveId);
		mv.addObject("roleid", roleid);
		mv.addObject("data", id==null||id==0 ? id : this.advertisingService.find(id));
		return mv;
	}

	/**
	 * 保存（更新）
	 * @param Live
	 * @return
	 */
	@RequestMapping("/save")
	public ModelAndView save(Advertising advertising) {
		ModelAndView mv = new ModelAndView();
		try {
			if(advertising.getId()==null) {
				advertising.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				this.advertisingService.save(advertising);
				mv.setViewName(this.viewName.concat("1"));
				mv.setViewName("redirect:/advertising/list/"+advertising.getLiveId());

			} else {
				this.advertisingService.update(advertising);
				mv.setViewName(this.viewName.concat("2"));
				mv.setViewName("redirect:/advertising/list/"+advertising.getLiveId());

				// 清理内容页缓存
        NginxPurgeCacheUtil.purge(6, advertising.getId());
			}
			// 清理内容页缓存
      NginxPurgeCacheUtil.purge(5, advertising.getId());
		} catch(Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "帮助中心问题保存异常！", e);
		}
		return mv;
	}
	
	@RequestMapping("/del/{id}")
	@ResponseBody
	public Map<String, Object>  del(@PathVariable Long id) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			this.advertisingService.delete(id);
		//	mv.setViewName(this.viewName.concat("3"));
			jsonMap.put("msg", "成功");
			// 清理文章缓存
      NginxPurgeCacheUtil.purge(2, id);
		} catch(Exception e) {
			jsonMap.put("msg", "失败");
		}
		return jsonMap;
	}
}
